from flask import request, jsonify
from app.extensions import db
from app.models import Chart, ChartSchema, Node, Relationship
from app.utils.auth import require_auth, get_current_user
from . import api_bp

chart_schema = ChartSchema()
charts_schema = ChartSchema(many=True)

@api_bp.route('/charts', methods=['GET'])
@require_auth
def get_charts(current_user):
    try:
        # 只返回当前用户的图表
        charts = Chart.query.filter_by(user_id=current_user.id, status='active').all()
        result = charts_schema.dump(charts)
        return jsonify({
            'code': 200,
            'message': 'success',
            'data': result
        })
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': str(e),
            'data': None
        }), 500

@api_bp.route('/charts/<int:chart_id>', methods=['GET'])
@require_auth
def get_chart(current_user, chart_id):
    try:
        chart = Chart.query.filter_by(id=chart_id, user_id=current_user.id).first()
        if not chart:
            return jsonify({
                'code': 404,
                'message': 'Chart not found',
                'data': None
            }), 404

        result = chart_schema.dump(chart)
        return jsonify({
            'code': 200,
            'message': 'success',
            'data': result
        })
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': str(e),
            'data': None
        }), 500

@api_bp.route('/charts', methods=['POST'])
@require_auth
def create_chart(current_user):
    try:
        data = request.get_json()

        # 如果设置为默认图，先取消当前用户的其他默认图
        if data.get('is_default'):
            Chart.query.filter_by(user_id=current_user.id, is_default=True).update({'is_default': False})

        # 设置用户ID
        data['user_id'] = current_user.id
        chart = Chart(**data)
        db.session.add(chart)
        db.session.commit()

        result = chart_schema.dump(chart)
        return jsonify({
            'code': 201,
            'message': 'Chart created successfully',
            'data': result
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': str(e),
            'data': None
        }), 500

@api_bp.route('/charts/<int:chart_id>', methods=['PUT'])
@require_auth
def update_chart(current_user, chart_id):
    try:
        chart = Chart.query.filter_by(id=chart_id, user_id=current_user.id).first()
        if not chart:
            return jsonify({
                'code': 404,
                'message': 'Chart not found',
                'data': None
            }), 404

        data = request.get_json()

        # 如果设置为默认图，先取消当前用户的其他默认图
        if data.get('is_default') and not chart.is_default:
            Chart.query.filter_by(user_id=current_user.id, is_default=True).update({'is_default': False})

        # 不允许修改user_id
        if 'user_id' in data:
            del data['user_id']

        for key, value in data.items():
            if hasattr(chart, key):
                setattr(chart, key, value)

        db.session.commit()
        result = chart_schema.dump(chart)
        return jsonify({
            'code': 200,
            'message': 'Chart updated successfully',
            'data': result
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': str(e),
            'data': None
        }), 500

@api_bp.route('/charts/<int:chart_id>', methods=['DELETE'])
@require_auth
def delete_chart(current_user, chart_id):
    try:
        chart = Chart.query.filter_by(id=chart_id, user_id=current_user.id).first()
        if not chart:
            return jsonify({
                'code': 404,
                'message': 'Chart not found',
                'data': None
            }), 404

        # 不能删除默认图
        if chart.is_default:
            return jsonify({
                'code': 400,
                'message': 'Cannot delete default chart',
                'data': None
            }), 400

        db.session.delete(chart)
        db.session.commit()
        return jsonify({
            'code': 200,
            'message': 'Chart deleted successfully',
            'data': None
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': str(e),
            'data': None
        }), 500

@api_bp.route('/charts/<int:chart_id>/duplicate', methods=['POST'])
@require_auth
def duplicate_chart(current_user, chart_id):
    try:
        original_chart = Chart.query.filter_by(id=chart_id, user_id=current_user.id).first()
        if not original_chart:
            return jsonify({
                'code': 404,
                'message': 'Chart not found',
                'data': None
            }), 404

        # 创建新图表
        new_chart = Chart(
            user_id=current_user.id,
            name=f"{original_chart.name} - 副本",
            description=original_chart.description,
            is_default=False,
            status='active'
        )
        db.session.add(new_chart)
        db.session.flush()  # 获取new_chart的ID

        # 复制节点
        original_nodes = Node.query.filter_by(chart_id=chart_id, status='active').all()
        node_id_mapping = {}

        for original_node in original_nodes:
            new_node = Node(
                chart_id=new_chart.id,
                name=original_node.name,
                type=original_node.type,
                description=original_node.description,
                position_x=original_node.position_x,
                position_y=original_node.position_y,
                color=original_node.color,
                size=original_node.size,
                status=original_node.status
            )
            db.session.add(new_node)
            db.session.flush()
            node_id_mapping[original_node.id] = new_node.id

        # 复制关系
        original_relationships = Relationship.query.filter_by(chart_id=chart_id, status='active').all()

        for original_rel in original_relationships:
            new_relationship = Relationship(
                chart_id=new_chart.id,
                upstream_node_id=node_id_mapping[original_rel.upstream_node_id],
                downstream_node_id=node_id_mapping[original_rel.downstream_node_id],
                relationship_type=original_rel.relationship_type,
                label=original_rel.label,
                strength=original_rel.strength,
                color=original_rel.color,
                status=original_rel.status
            )
            db.session.add(new_relationship)

        db.session.commit()

        result = chart_schema.dump(new_chart)
        return jsonify({
            'code': 201,
            'message': 'Chart duplicated successfully',
            'data': result
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': str(e),
            'data': None
        }), 500

@api_bp.route('/charts/default', methods=['GET'])
@require_auth
def get_default_chart(current_user):
    try:
        # 获取当前用户的默认图表
        chart = Chart.query.filter_by(user_id=current_user.id, is_default=True, status='active').first()

        # 如果没有默认图表，返回用户的第一个图表
        if not chart:
            chart = Chart.query.filter_by(user_id=current_user.id, status='active').first()

        if not chart:
            return jsonify({
                'code': 404,
                'message': 'No chart found',
                'data': None
            }), 404

        result = chart_schema.dump(chart)
        return jsonify({
            'code': 200,
            'message': 'success',
            'data': result
        })
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': str(e),
            'data': None
        }), 500